package cn.ad.server.web.spring.service.httpclient4;

import cn.ad.server.web.spring.service.components.http.client.AdResponseHandler;
import cn.ad.server.web.spring.service.components.http.client.ResponseHandleException;
import cn.ad.server.web.utils.JsonUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

/**
 * 处理响应返回map
 * @author wangwei
 *
 */
public class MapResponseHandler implements AdResponseHandler<Map> {
	
	private static Logger LOGGER = LoggerFactory.getLogger(MapResponseHandler.class);
	
	@Override
	public Map doHandle(Object response) throws ResponseHandleException {
		if(response==null){
			throw new ResponseHandleException("处理响应的资源不存在。");
		}
		if(response instanceof HttpResponse){			
			try {
				return handleResponse((HttpResponse)response);
			} catch (Exception e) {
				throw new ResponseHandleException("handle Response error :" + e.getMessage(),e.getCause());
			}
		}
		throw new ResponseHandleException("The Request is not support. class:" + response.getClass().getName());
	}

	
	Map handleResponse(HttpResponse response) throws UnsupportedOperationException, IOException {
		InputStream ins = response.getEntity().getContent();
         if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
        	 Map result = JsonUtils.toObject(ins, Map.class);
        	 return result;
         }
         return null;
	}
	

}
